import _ from 'lodash';
import MockProcessor from './mock/mock-processor.js';

/**
 * 请求成功拦截器。不能使用箭头函数，否则无this
 * @param axiosRequestConfig {}
 * @returns {any}
 */
const handleRequestFulfilled = function handleRequestFulfilled(axiosRequestConfig) {
  const reqConfig = _.defaultsDeep(axiosRequestConfig, this.options);
  
  // 添加请求头信息，例如权限验证token请求头
  this.options.addRequestHeaders(reqConfig.headers);
  
  // 请求发送到响应过程中的loading
  if (reqConfig.loading) {
    reqConfig.showLoading();
  }
  
  // 表单数据以键值对的形式发送
  if (reqConfig.requestBodyFormUrlEncoded) {
    reqConfig.headers['content-type'] = 'application/x-www-form-urlencoded';
    
    const params = new URLSearchParams();
    _.forOwn(reqConfig.data, (value, key) => {
      params.append(key, value);
    });
    reqConfig.data = params;
  }
  
  // Mock数据构造器
  const mockProcessor = new MockProcessor({
    axiosRequestConfig: reqConfig,
  });
  mockProcessor.process();
  
  return reqConfig;
};

export default handleRequestFulfilled;
